//
//  WFWebViewController.m
//  WFTravel
//
//  Created by admin on 2017/11/16.
//  Copyright © 2017年 lg. All rights reserved.
//

#import "LLWebViewController.h"
#import <WebKit/WebKit.h>
#import "LLSaveImageTool.h"
#import <WXApi.h>
#import "TTDianpuShareView.h"

@interface LLWebViewController ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic , strong) WKWebViewConfiguration *configuration;

@property (nonatomic, strong) NSString *urlString;
@property (nonatomic, strong) NSString *htmlString;

///如果是pdf文件，显示保存按钮
@property (nonatomic, strong) UIButton *savePdfBtn;

@property (nonatomic, strong) TTDianpuShareView *shareView;
@property (nonatomic, strong) UIImage *shareImage;

@end

@implementation LLWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    RAC(self.progressView,progress) = RACObserve(self.webView, estimatedProgress);
    RAC(self.progressView,hidden) = [RACObserve(self.webView, estimatedProgress) map:^id _Nullable(NSNumber *value) {
        double progress  = value.doubleValue;
        return @(progress == 1.0);
    }];
    
    
}

- (void)setWebTitle:(NSString *)webTitle
{
    _webTitle = webTitle;
    if (webTitle) {
        self.title = webTitle;
    }
}

- (void)setUrlString:(NSString *)urlString htmlString:(NSString *)htmlString
{
    if (urlString.length > 0) {
        self.urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
        [self.webView loadRequest:request];
        
        if ([urlString hasSuffix:@".pdf"]) {
            self.view.backgroundColor = [UIColor blackColor];
            _webView.opaque = NO;
            _webView.backgroundColor = [UIColor blackColor];
            self.savePdfBtn.hidden = NO;
            
            UIImage *shareImage = [[UIImage imageNamed:@"fenxiang"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:shareImage style:UIBarButtonItemStylePlain target:self action:@selector(rightShareActin)];
        }
        
    }
    
    if (htmlString.length > 0) {
        [self.webView loadHTMLString:htmlString baseURL:nil];
    }
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"playJiezhiVideo"]) {
        
        
    }
}


#pragma mark - WKNavigationDelegate
// 加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    if (self.webTitle.length == 0) {
        self.title = webView.title;
    }
}

// 失败
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"error 出错了==== %@", error);
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSString *urlString = navigationResponse.response.URL.absoluteString;
    NSLog(@"%@", urlString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}


#pragma mark - WKUIDelegate
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}

//保存pdf文件转图片到相册
- (void)savePdfBtnClick
{
    if (self.shareImage) {
        [[LLSaveImageTool new] saveImage:self.shareImage];
        return;
    }
    
    NSURL *url = [NSURL URLWithString:self.urlString];
    [MBProgressHUD showLoadingAnimationOnView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSData *pdfData = [NSData dataWithContentsOfURL:url];
        self.shareImage = [UIImage imageWithPDF:pdfData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD dismissAnimationOnView:self.view];
            [[LLSaveImageTool new] saveImage:self.shareImage];
        });
        
    });
}


///分享
- (void)rightShareActin
{
    if (self.shareImage == nil) {
        //下载图片
        NSURL *url = [NSURL URLWithString:self.urlString];
        [MBProgressHUD showLoadingAnimationOnView:self.view];
        NSData *pdfData = [NSData dataWithContentsOfURL:url];
        self.shareImage = [UIImage imageWithPDF:pdfData];
        [MBProgressHUD dismissAnimationOnView:self.view];
    }
    
    if (self.shareView == nil) {
        self.shareView = [TTDianpuShareView shareViewWithTitles:@[@"分享证书到朋友圈", @"分享证书给好友"] selectBlock:^(NSInteger index) {
            
            NSString *selStr = [NSString stringWithFormat:@"shareTo_%ld", index];
            SEL sel = NSSelectorFromString(selStr);
            if ([self respondsToSelector:sel]) {
                IMP imp = [self methodForSelector:sel];
                void (*func)(id, SEL) = (void *)imp;
                func(self, sel);
            }
        }];
    }
    
    [LLAnimationAlertView animationAlertViewWithView:self.shareView animationType:AnimationFromBottom];
    
}


///朋友圈
- (void)shareTo_0
{
    [self shareImageToWeixinWIthType:WXSceneTimeline];
}

///朋友
- (void)shareTo_1
{
    [self shareImageToWeixinWIthType:WXSceneSession];
}

- (void)shareImageToWeixinWIthType:(int)type
{
    NSData *imageData = UIImageJPEGRepresentation(self.shareImage, 0.7);
       
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = imageData;

    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = imageObject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = type;
    [WXApi sendReq:req completion:^(BOOL success) {
        NSString *str = success ? @"分享成功" : @"分享失败";
        [[UIApplication sharedApplication].keyWindow makeToast:str];
    }];
}



- (WKWebView *)webView
{
    if (!_webView) {
        self.configuration = [[WKWebViewConfiguration alloc] init];
        self.configuration.userContentController = [[WKUserContentController alloc] init];
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [self.view addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
            make.left.right.equalTo(self.view);
        }];
    }
    return _webView;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.progressTintColor = kMainColor;
    }
    return _progressView;
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.progressView.frame = CGRectMake(0, self.navigationController.navigationBar.height - 1, self.view.width, 1);
    [self.navigationController.navigationBar addSubview:self.progressView];
}

- (UIButton *)savePdfBtn
{
    if (!_savePdfBtn) {
        _savePdfBtn = [UIButton createButtonWithTitle:@"保存到相册" titleColor:[UIColor whiteColor] titleFontSize:15 borderColor:[UIColor whiteColor] cornerRadius:20 contentEdgeInsets:UIEdgeInsetsMake(10, 40, 10, 40) target:self action:@selector(savePdfBtnClick)];
        _savePdfBtn.hidden = YES;
        [self.webView addSubview:_savePdfBtn];
        [_savePdfBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-50);
            make.centerX.equalTo(self.webView);
            make.height.mas_equalTo(40);
        }];
    }
    return _savePdfBtn;
}


-(void)dealloc
{
    [self.progressView removeFromSuperview];
}


@end
